package com.zhiche.wms.configuration;

import com.alibaba.fastjson.JSONObject;
import com.zhiche.wms.core.supports.BaseException;
import com.zhiche.wms.core.supports.enums.ExceptionCodeDetailEnum;
import com.zhiche.wms.dto.base.ResultDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

@RestControllerAdvice
public class GlobalExceptionHandler {

    private Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 所有异常报错
     */
    @ExceptionHandler(value = Exception.class)
    public String allExceptionHandler(HttpServletRequest request,
                                      Exception exception) {
        logger.error("LOGGER [       ERROR]:" + "[--" + Thread.currentThread().getName() + "--]" + request.getRequestURI() + " [       error]:{}" , exception.getMessage());
        // 判断发生异常的类型是除0异常则做出响应
        ResultDTO<Object> response = new ResultDTO<>(false);
        if (exception instanceof BaseException) {
            response.setCode(Integer.valueOf(ExceptionCodeDetailEnum.BASE_EXP_11.getCode()));
            response.setMessage(exception.getMessage());
        } else {
            response.setCode(Integer.valueOf(ExceptionCodeDetailEnum.BASE_EXP_11.getCode()));
            response.setMessage(ExceptionCodeDetailEnum.BASE_EXP_500.getDetail());
        }
        return JSONObject.toJSONString(response);
    }

}
